/**
 * NFC相关工具函数
 */

const app = getApp();

/**
 * 检查设备是否支持NFC
 * @returns {boolean}
 */
export function isNFCSupported() {
  return app.globalData.nfcSupported;
}

/**
 * 获取当前NFC设备信息
 * @returns {object|null}
 */
export function getCurrentNFCDevice() {
  return app.globalData.nfcDevice;
}

/**
 * 手动启动NFC监听
 */
export function startNFCListener() {
  if (app.globalData.nfcSupported) {
    app.startNFCListener();
  }
}

/**
 * 停止NFC监听
 */
export function stopNFCListener() {
  app.stopNFCListener();
}

/**
 * 检查NFC适配器是否可用
 * @returns {boolean}
 */
export function checkNFCAdapter() {
  try {
    const nfcAdapter = wx.getNFCAdapter();
    return !!nfcAdapter;
  } catch (error) {
    console.error('NFC适配器检查失败:', error);
    return false;
  }
}

/**
 * 检查NFC API兼容性
 * @returns {object} 兼容性信息
 */
export function checkNFCCompatibility() {
  const compatibility = {
    supported: false,
    adapter: false,
    discovered: false,
    startDiscovery: false,
    stopDiscovery: false
  };

  try {
    // 检查基础API是否存在
    if (typeof wx.getNFCAdapter === 'function') {
      compatibility.supported = true;

      const nfcAdapter = wx.getNFCAdapter();
      if (nfcAdapter) {
        compatibility.adapter = true;

        // 检查具体方法是否存在
        compatibility.discovered = typeof nfcAdapter.onDiscovered === 'function';
        compatibility.startDiscovery = typeof nfcAdapter.startDiscovery === 'function';
        compatibility.stopDiscovery = typeof nfcAdapter.stopDiscovery === 'function';
      }
    }
  } catch (error) {
    console.error('NFC兼容性检查失败:', error);
  }

  return compatibility;
}

/**
 * 解析NFC设备类型
 * @param {string} type NFC设备类型
 * @returns {string} 友好的类型名称
 */
export function parseNFCType(type) {
  if (!type) return '未知';

  const typeMap = {
    'nfc-a': 'NFC-A (ISO14443A)',
    'nfc-b': 'NFC-B (ISO14443B)',
    'nfc-f': 'NFC-F (FeliCa)',
    'nfc-v': 'NFC-V (ISO15693)',
    'iso-dep': 'ISO-DEP',
    'mifare-classic': 'Mifare Classic',
    'mifare-ultralight': 'Mifare Ultralight',
    'mifare-desfire': 'Mifare DESFire',
    'felica': 'FeliCa',
    'iso15693': 'ISO15693'
  };

  return typeMap[type.toLowerCase()] || type;
}

/**
 * 获取NFC设备厂商信息
 * @param {object} deviceInfo NFC设备信息
 * @returns {string} 厂商名称
 */
export function getNFCManufacturer(deviceInfo) {
  if (!deviceInfo) return '未知厂商';

  // 根据设备ID或其他信息判断厂商
  const id = deviceInfo.id || '';
  const manufacturer = deviceInfo.manufacturer || '';

  if (manufacturer) return manufacturer;

  // 根据ID前缀判断常见厂商
  if (id.startsWith('04')) return 'NXP Semiconductors';
  if (id.startsWith('08')) return 'Sony';
  if (id.startsWith('0C')) return 'Infineon Technologies';
  if (id.startsWith('10')) return 'STMicroelectronics';

  return '未知厂商';
}

/**
 * 格式化NFC设备信息
 * @param {object} rawData 原始NFC数据
 * @returns {object} 格式化的设备信息
 */
export function formatNFCDeviceInfo(rawData) {
  return {
    id: rawData.id || '未知',
    type: rawData.type || '未知',
    name: rawData.name || '未知设备',
    manufacturer: getNFCManufacturer(rawData),
    model: rawData.model || '未知型号',
    serialNumber: rawData.serialNumber || rawData.id || '未知序列号',
    friendlyType: parseNFCType(rawData.type),
    timestamp: new Date().toLocaleString(),
    rawData: rawData
  };
}

/**
 * 显示NFC设备信息弹窗
 * @param {object} deviceInfo 设备信息
 */
export function showNFCDeviceModal(deviceInfo) {
  const formattedInfo = formatNFCDeviceInfo(deviceInfo);

  wx.showModal({
    title: '发现NFC设备',
    content: `设备名称：${formattedInfo.name}\n设备类型：${formattedInfo.friendlyType}\n厂商：${formattedInfo.manufacturer}\n序列号：${formattedInfo.serialNumber}`,
    showCancel: false,
    confirmText: '确定'
  });
}

/**
 * 检查NFC权限
 * @returns {Promise<boolean>}
 */
export function checkNFCPermission() {
  return new Promise((resolve) => {
    if (!isNFCSupported()) {
      resolve(false);
      return;
    }

    // 尝试获取NFC适配器来检查权限
    try {
      const nfcAdapter = wx.getNFCAdapter();
      resolve(true);
    } catch (error) {
      console.error('NFC权限检查失败:', error);
      resolve(false);
    }
  });
}

/**
 * 请求NFC权限
 * @returns {Promise<boolean>}
 */
export function requestNFCPermission() {
  return new Promise((resolve) => {
    wx.showModal({
      title: '需要NFC权限',
      content: '为了识别NFC设备，需要获取NFC权限',
      success: (res) => {
        if (res.confirm) {
          // 尝试初始化NFC
          try {
            app.initNFC();
            resolve(true);
          } catch (error) {
            console.error('NFC权限请求失败:', error);
            resolve(false);
          }
        } else {
          resolve(false);
        }
      }
    });
  });
}
